package myPack1;

import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Ajax_Handling {
	
	WebDriver driver;
	String url;
	
	@Before
	public void launchBrowser() throws Exception{
		driver = new FirefoxDriver();
		
		driver.manage().window().maximize();
		
		url = "http://www.makemytrip.com/";
		
		//driver.manage().timeouts().setScriptTimeout(60, TimeUnit.SECONDS);
		
		//driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
		
		driver.manage().timeouts().implicitlyWait(45, TimeUnit.SECONDS);
		
		
		/*
		 * Ajax is combination of JavaScript ans XMl, it makes async. request 
		 * to the server and get/display data on page without refresh it
		 */
		
	}
	
	@Test
	public void atTest() throws Exception{
		//Test Case logic
		
		driver.get(url);
		driver.findElement(By.id("from_typeahead1")).sendKeys("Delhi");
		//Thread.sleep(1000);
		
		String a = "//html/body/div[6]/div[1]/div/div/div[1]/div/div[3]/div/div[5]/div/div[1]/div/div[1]/span/span/div/span/div[";

		int i = 1;

		String b = "]/p";

		String xp = a + i + b;
		
		try{
			while(driver.findElement(By.xpath(xp)).isDisplayed()){
				xp = a + i + b;
				
				//System.out.println(driver.findElement(By.xpath(xp)).getText());
				String text = driver.findElement(By.xpath(xp)).getText();
				System.out.println(text);
				if(text.contains("Gurgaon")){
					System.out.println("Gurgaon city is found.");
					driver.findElement(By.xpath(xp)).click();
					break;
				}
				
				i++;			
			}
		}catch(Exception e){
			System.out.println("All element has been read.");
		}
		
	}	
	@After
	public void atAfter() throws Exception{
		
	}

}
